package com.fbs.wowo.finance.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    public static String post(String url) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        return post(httpclient, httpPost);
    }
    /**
     * 发送json格式参数请求
     * @return
     */
    public static String postXml(String url, String jsonParams) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        if (jsonParams != null) {
            StringEntity stringEntity = new StringEntity(jsonParams, "utf-8");
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.setEntity(stringEntity);
        }

        return post(httpclient, httpPost);
    }

    public static String post(String url, Map<String, String> paramPairs) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<>();
        // 遍历 paramPairs 获取键和值
        paramPairs.forEach((key, value) -> {
            nvps.add(new BasicNameValuePair(key, value));
        });

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps);
        httpPost.setEntity(formEntity);

        return post(httpclient, httpPost);
    }

    /**
     * 需要证书的请求
     * @return
     */
//    public static String post(String url, String entity, InputStream certStream, char[] password) throws IOException {
//        BasicHttpClientConnectionManager connManager = null;
//        // 证书
//        try {
//            KeyStore ks = KeyStore.getInstance("PKCS12");
//            ks.load(certStream, password);
//
//            // 实例化密钥库 & 初始化密钥工厂
//            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//            kmf.init(ks, password);
//
//            // 创建 SSLContext
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
//
//            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
//                    sslContext,
//                    new String[]{"TLSv1"},
//                    null,
//                    new DefaultHostnameVerifier());
//
//            connManager = new BasicHttpClientConnectionManager(
//                    RegistryBuilder.<ConnectionSocketFactory>create()
//                            .register("http", PlainConnectionSocketFactory.getSocketFactory())
//                            .register("https", sslConnectionSocketFactory)
//                            .build(),
//                    null,
//                    null,
//                    null
//            );
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println(e.getMessage());
//        }
//        CloseableHttpClient httpClient = HttpClientBuilder.create()
//                .setConnectionManager(connManager)
//                .build();
//
//        HttpPost httpPost = new HttpPost(url);
//        if (entity != null) {
//            StringEntity stringEntity = new StringEntity(entity, "utf-8");
//            httpPost.setEntity(stringEntity);
//        }
//        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
//        httpPost.setConfig(requestConfig);
//        httpPost.addHeader("Content-Type", "text/xml");
//        return post(httpClient, httpPost);
//    }

    public static Object get() {
        return null;
    }

    private static String post(CloseableHttpClient httpclient, HttpPost httpPost) throws IOException {
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            HttpEntity entity = response.getEntity();
            String str = EntityUtils.toString(entity, "UTF-8");
//            if (statusCode / 100 != 2) {
//                throw new IOException("错误");
//            }

            EntityUtils.consume(entity);
            return str;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            response.close();
        }
    }
}
